import Addition2 from '@/components/Addition2';
import {s_saveMaterialUserDefine, s_getMaterialCategoryTree, s_getMaterialDocument, s_getMaterialUserDefine, s_getOrgTargetKeysGlobal, s_getOrgTransferData, s_saveAllocateOrgGlobal, s_saveMaterialInfo, s_saveUnitData, getCommTreeByXid, s_getTableInfo, s_updateInfo, s_getSelectData } from '@/services/basis';
import { getSelection } from '@/services/selections';
import { ActionType, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable } from '@ant-design/pro-components';
import { useModel, useRequest } from '@umijs/max';
import { Card,Image, theme,Row,Col,Tree, Space, Button, Form, Input, Modal, Radio, Select, DatePicker, Drawer, Transfer, Divider, Checkbox, Tabs, TabsProps, message} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
 
import dayjs from 'dayjs';
import moment from 'moment';
import React, { useRef, useState } from 'react';

//物料分类组件
 function CategoryTree(props:any){
  return(
    <Tree treeData={props.tdata}   expandedKeys={props.expandKeys}
       blockNode={true}
       onClick={(e,node)=>{props.getTreeInfo(node);}}/>
  );
}


//物料档案表组件-- 注意：table_ref用于外部控制表格还原
// function MaterialTable({tdata,setMaterialCode,table_ref}){
  
  interface DataType{
    pic?:string,
    x_id:number,
    id:number, 
    cate_id:number,
    code:string,
    name:string,
    scode:string,
    cate_code:string,
    invstd:string,
    invstd2:string,
    brand:string,
    isservice:number,
    isfee:number,
    munit_code:string,
    aunit_code:string,
    rate:number,
    status:number,
    operate_time:string,
    operater_code:string,
    fnsku:string,ansi:string,
    //以下4个为视图中添加
    cate_name:string,
    operater_name:string,
    munit_name:string,
    aunit_name:string,
    munit_id?:number,
    aunit_id?:number,
    default_type?:number,
    default_type_name?:string,
  }

   const columns:ProColumns<DataType>[]=[
    {dataIndex:'pic',title:'图片' ,editable:false,width:60,search:false,
          render:(text:any)=>{
              var pic=text=="-"||text==undefined||text==false||text==null?'':"/basis_api/file/get?filename="+text.toString();
              return <Image src={pic}  
                     style={{width:50,height:50}} alt='无' />
         }},
    {
      dataIndex:'cate_name',
      title:'物料分类',search:false,
    },
    {
      dataIndex:'code',
      title:'物料编码',
    }, {
      dataIndex:'name',
      title:'名称',
    },{
      dataIndex:'scode',
      title:'简码',search:false,
    },
    {
      dataIndex:'ansi',
      title:'ANSI',search:false,
    },
    {
      dataIndex:'fnsku',
      title:'FNSKU',search:false,
    },
   {
      dataIndex:'invstd',
      title:'规格',
    },{
      dataIndex:'invstd2',
      title:'型号',search:false,
    },{
      dataIndex:'munit_name',
      title:'主计量单位',search:false,
    },{
      dataIndex:'aunit_name',
      title:'辅计量单位',search:false,
    },{
      dataIndex:'rate',search:false,
      title:'换算率',
    },{
      dataIndex:'brand',search:false,
      title:'品牌',
    },{
      dataIndex:'isservice',search:false,
      title:'是否服务',
      render:(text)=>text===1?<>是</>:<>否</>,
    },{
      dataIndex:'isfee',search:false,
      title:'是否费用',
      render:(text)=>text===1?<>是</>:<>否</>,
    },
    {
      dataIndex:'default_type_name',title:'默认来源',search:false,
    },
    {
      dataIndex:'status',
      title:'状态',
      valueType:'radio',
      fieldProps:{
        options:[{value:1,label:'正常'},{value:2,label:'关闭'},{value:3,label:'删除'}]
      }
      // render:(text)=>text===1?<>启用</>:<Space style={{color:'red'}}>{text===2?<>停用</>:<>删除</>}</Space>,
    },
   ];

  
//物料自由项表，作为定义项--要调出所有自由项，并勾选
function MaterialUserDefine(props:any){

 //监控自定义值的变化.type代表更新的字段：1 item_id,2 ismust,3 status
 function update(e:any,id:number,type:number){
  const x=props.udata.map((item:any)=>{
      if(item.userdefine_id===id){
          if(type===1)
              return {...item,item_code:e.target.checked?1:0};
          else if(type===2)
              return {...item,ismust:e.target.value};
          else
              return {...item,status:e.target.value};
      }
     else
         return item;
  });

  //更新新值到staate, 同步渲染新表格--关键
  props.setUdata(x);
}

   interface DataType{
    apply_id:number,
    item_code:number,
    status:number,
    ismust:number,
    userdefine_id:number,
    code:string,
    name:string,
    //默认物料source_type=1
   } ;

   const columns:ProColumns<DataType>[]=[
    {
      dataIndex:'userdefine_id',
      title:'ID',
    },
    {
      dataIndex:'code',
      title:'自由项编码',
    },
    {
      dataIndex:'name',
      title:'自由项名称',
    },
    {
      dataIndex:'item_code',
      title:'选择',
      render:(text,record)=>
      <Checkbox checked={text===1?true:false} 
      // disabled={record.status===1?false:true}
          onChange={(e)=>update(e,record.userdefine_id,1)}>
      </Checkbox>
      
    },
    {
      dataIndex:'ismust',
      title:'取值类型',
      render:(text,record)=><Radio.Group value={text}  
      // disabled={record.status===1?false:true}
      onChange={(e)=>update(e,record.userdefine_id,2)}>
                        <Radio value={1}>必填</Radio>
                        <Radio value={0}>非必填</Radio>
                     </Radio.Group>
    },
    {
      dataIndex:'status',
      title:'状态',
      render:(text,record)=><Radio.Group value={text} 
      // disabled={text===1?false:true}
      onChange={(e)=>update(e,record.userdefine_id,3)}>
                        <Radio value={1}>启用</Radio>
                        <Radio value={2}>冻结</Radio>
                        <Radio value={3}>非选项</Radio>
                    </Radio.Group>
    },
   ];  

  // alert('这是控件内：'+JSON.stringify(udata));
   return(
    <ProTable 
    dataSource={props.udata} 
    columns={columns} 
    rowKey='id' 
   // rowSelection={{
    //  type:'radio',
    //  onChange:(selectedKeys,selectedRows)=>setUdata(selectedRows),    
   //  }}
    //onRow={(record)=>{return{onClick:()=>setUdata(record)}}}
    />
   );
}
 

interface DataType3{
  // id,x_id,material_id,custom_id,cmaterial_code,
  // cmaterial_id,status,custom_code,custom_name
  id?:number,x_id?:number,material_id?:number,custom_id?:number,cmaterial_code?:string,
  cmaterial_id?:number,status?:number,custom_code?:string,custom_name?:string
};



const Welcome: React.FC = () => {
  //选中的物料分类码。因需用于新增表单中，故{}
  const [selectedCategory,setSelectedCategory]=useState(0);       //选择的分类ID
  const [selectedCateNode,setSelectedNode]=useState<{title:string}>();            //选择的树节点
  const [treeData,setTreeData]=useState();                        //分类树数据源
  const [tdata,setTdata]=useState();                               //档案表格数据源
  const [selectedRecords,setSelectedRecords]=useState<DataType[]>([]);           //选中的物料编码,

  const [openInfo,setOpenInfo]=useState(false);//显示物料档案窗口
  const [openAllocate,setOpenAllocate]=useState(false);//显示物料分配窗口
  const [openDefine,setOpenDefine]=useState(false);//显示物料定义窗口
  const [etype,setEtype]=useState(0);   //1新增 0修改
  const [materialParam,setMaterialParam]=useState({});

  const [dtype,setDtype]=useState(1);//店铺对照时，新增或编辑标识
  const [dopen,setDopen]=useState(false);//店铺对照编辑框显示标识
  const [selectedCompare,setSelectedCompare]=useState<DataType3[]>([]);
  const form_ref3=useRef<ProFormInstance>();//店铺对照表单
  const [submittable,setSubmittable]=useState(false);//店铺对照表保存按钮是否可执行

  const [selectedKeys,setSelectedKeys]=useState<any[]>([]);//树选择的本级节点及下节点

  //const [orgtransfer,setOrgtransfer]=useState();//穿梭框数据源
  const [orgtargetkeys,setOrgtargetkeys]=useState([]);//穿梭框的已选中值
  const [addition,setAddition]=useState([]);

   //定义物料自由项
   const [udata,setUdata]=useState([]);//在表格中更新选择状态

   //定义计量单位 组件数据源
   const [uintSelection,setUintSelection]=useState([]);

   const eform_ref=useRef<ProFormInstance>();//物料编辑表单
   const table_ref=useRef<ActionType>();//用于向物料档案组件表传递引用
   const formref_param=useRef<ProFormInstance>();
   const table_ref3=useRef<ActionType>();

   const [expandKeys,setExpandKeys]=useState([]);
   const [materialCode,setMaterialCode]=useState('');//监控物料编码变化，非空时允许上传附件
   const [treeCate,setTreeCate]=useState<any>();//左侧树选中后，展开的下级分类，用于物料明细筛选
   
   
    //在MODEL中,定义FORM供调用
  // const orgtransfer=useModel('getOrgTransfer');//角色分配的组织穿梭框数据源--直接使用
 
 //此处创建一个生成树的通用方法，通过传入表名和X_ID值
 useRequest(()=>getCommTreeByXid({x_id:1,source_table:'material_category'}),{  
  onSuccess:(data)=>{
    setTreeData(data.ctree);
    setExpandKeys(data.keys);
  },
});

  //获取存货档案表
//  useRequest(()=>s_getMaterialDocument({x_id:1,cate_id:[],id:0}),{
//          onSuccess:(data:any)=>{
//           //  alert(JSON.stringify(data));
//             setTdata(data[0]);
//          },
//      }
//   );

//获取计量单位表
useRequest(()=>getSelection({source:'base_unit',code:'999'}),{
    onSuccess:(data:any)=>{
      const x=data.map((item:any)=>({value:item.code,label:item.name}));
      setUintSelection(x);
    }
});
 
  //根据左侧选择的类别，右侧表格显示明细--注意：此处传入的是树节点node(key,title) 
  //---先取本节点及下级节点值，再共同选---------------------------------------------开始-----------------
  var arr:any[]=[];
   //定义一个递归函数，获取选中节点下的所有key
   function getNodeKeys(node:{key:any,title:any,children:any[]}){
        if(node.children.length>0)
              node.children.map((item:any)=>{
                 arr.push(item.key);
                 if(item.children.length>0){
                      arr.push(getNodeKeys(item));
                 }
             });
      }

  async function getMaterial(node:any){
     // alert( (curCategory));
      setSelectedRecords([]);
      setSelectedCategory(node.key);
      setSelectedNode(node);
     
     arr=[];//先置为空，再取数据
     arr.push(node.key);
     getNodeKeys(node);
     setSelectedKeys(arr.filter((item)=>item!=null));//当前选中的组织的所有下级ID
     setTreeCate(arr);
      // const x=await s_getMaterialDocument({x_id:1,cate_id:arr,id:0});
     //alert(JSON.stringify(x.data[0]));
    //  setTdata(x.data[0]);
    
     table_ref.current?.reset?.();
  }
 //---先取本节点及下级节点值，再共同选---------------------------------------------结束-----------------

  //新增物料信息
  async function addMaterialInfo(){
       if(selectedCategory===0)
          message.warning('请先选择物料分类。');
       else{
          setEtype(1);
          //根据选
           //参数source_type:1为物料，2为客商（暂未使用）
          const x=await s_getMaterialUserDefine({x_id:1,source_type:1,item_id:0});  

         //物料自由项
          setUdata(x.data[0]);
          setOpenInfo(true);
       }
  }

  //编辑物料信息
  async function editMaterialInfo(){
     if(selectedRecords.length===0)
         message.warning('请先选择要修改的物料。');
      else{
        setEtype(0);
        setMaterialCode(selectedRecords[0].code); 
      //新增：编辑物料自由项
       const m=await s_getMaterialUserDefine({x_id:1,source_type:1,item_id:selectedRecords[0]?.id});  
        //  alert(JSON.stringify(m.data[0]));
       setUdata(m.data[0]);
       //新增：编辑物料属性 2025-03-14
       const p=await s_getTableInfo({source:'material_param',id:selectedRecords[0].id});
        //  alert(JSON.stringify(p.data));
       setMaterialParam(p.data[0]);

       setOpenInfo(true);
      };
  }

  //保存物料编辑信息
  async function saveMaterialInfo(){
     //先取表单的数据，再保存。
     const fdata0=eform_ref.current?.getFieldsValue();
     if(fdata0.munit_id==undefined||fdata0.code==undefined||fdata0.name==undefined||fdata0.default_type==undefined)
         message.warning('物料编码、名称、主计量单位、默认来源，均不能为空，请检查');
    else{
     const pdata=formref_param.current?.getFieldsValue();//物料参数
     const fdata={...fdata0,id:selectedRecords[0]?.id,cate_id:etype===1?selectedCategory:selectedRecords[0]?.cate_id,
                   operate_time:moment(moment(fdata0.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss'),
                   //2025-03-14添加参数
                   param:pdata,
                  };
     // alert('自由项内容：'+JSON.stringify(udata));
    //  alert(JSON.stringify(fdata));
     //调用远程服务保存//保存基本信息    
     const x=await s_saveMaterialInfo({x_id:1,operater_id:1,etype,fdata});
     //保存自定义信息
     // alert(JSON.stringify(selectedRecords[0]));
     const y=await s_saveMaterialUserDefine({x_id:1,operater_id:1,item_id:selectedRecords[0]?.id,fdata:udata}); 
                
     if(x.success){
        message.success('数据保存成功。');
        // setOpenInfo(false);
        setEtype(0);
        setTdata(x.data);
        setUdata(y.data);
        //更新物料档案表
        table_ref.current?.reset?.();
      }
      else
        message.error('数据保存失败，请检查。');
  };
};

 
  //定义窗体引用
  const [formInfo]=Form.useForm();      //物料信息
  const [formAllocate]=Form.useForm();  //物料分配
  const [formDefine]=Form.useForm();    //物料定义
   
  //调用组织分配的界面
  async function allocateOrg(){
    if(selectedRecords.length===0)
        message.warning('请先选择要分配的物料。');
    else{
   //定义组织分配的数据源 s_getOrgTargetKeysGlobal({item_type,item_code})获取已分配的组织CODE
  // s_getOrgTransfetData（）获取组织列表，返回[{code,name}],需进一步组装为[{key,title}]
   //const x=await s_getOrgTransferData({});   
   //alert(JSON.stringify(orgtransfer2));                                     //--通用--
   //setOrgtransfer(orgtransfer2?.map((item:any)=>{return {key:item.code,title:item.name}}));
   //注意：要先获取item_code对应具体的物料编码---selectedCode
   
   const y=await s_getOrgTargetKeysGlobal({x_id:1,item_type:6,item_id:selectedRecords[0]?.id}); //---通用---
   const y0=y.data.map((item:any)=>item.id);
   //设置state
   //alert(JSON.stringify(x0));
  // alert(JSON.stringify(y));
   //setOrgtransfer(x0);
   setOrgtargetkeys(y0);
    setOpenAllocate(true)
     }
  }

  //保存分配组织
  async function saveAllocateOrgRole(){
    const x=await s_saveAllocateOrgGlobal(
         {x_id:1,operater_id:1,item_type:6,item_id:selectedRecords[0]?.id,fdata:orgtargetkeys});
    if(x.success){
      message.success('数据保存成功。');
      setOpenAllocate(false);
      
    }
    else
      message.error('数据保存失败，请检查');
  }
  
  const columns3:ProColumns<DataType3>[]=[
    // id,x_id,material_id,custom_id,cmaterial_code,
    // cmaterial_id,status,custom_code,custom_name
    {dataIndex:'id',title:'id',},{dataIndex:'x_id',title:'x_id',},
    {dataIndex:'material_id',title:'物料ID',},{dataIndex:'custom_id',title:'店铺ID',},
    {dataIndex:'custom_code',title:'店铺编码',},{dataIndex:'custom_name',title:'店铺名称',},
    {dataIndex:'cmaterial_id',title:'店铺物料ID',},{dataIndex:'cmaterial_code',title:'店铺物料编码',},
     
  ];

  async function addCompare(){
    setDtype(1);
    setDopen(true);
  }

  async function editCompare(){
    if(selectedCompare.length==0)
        message.warning('请选择要编辑的对照');
    else{
        
       setDtype(0);
       setDopen(true);
    }
  }

  async function saveCompare(n:number){
    // 参数：1保存，2保存并继续
    var fdata=form_ref3.current?.getFieldsValue();
    if(dtype==1)
        fdata={...fdata,material_id:selectedRecords.length>0?selectedRecords[0].id:0};
    // alert(JSON.stringify(fdata));
    const y=form_ref3.current?.submit();
    // alert(JSON.stringify(y));
    const x=await s_updateInfo({x_id:1,source:'material_code_custom',operater_id:1,fdata,etype:dtype});
    if(x.success){
        message.success('保存对照成功');
        table_ref3.current?.reloadAndRest?.();
        if(n==1)
          setDopen(false);
        else
          form_ref3.current?.resetFields?.();
    }else
       message.error('保存失败。请联系管理员')
  }

  // 监督窗体必填项2025-03-16
  

  //定义物料详细信息标签，以Tabs显示
  const items:TabsProps['items']=[
    {
      key:'1',
      label:'基本信息',
      children:<>
       <ProForm formRef={eform_ref} name='eform'
        submitter={false} layout='horizontal' labelAlign='left'  
        initialValues={etype==0?{...selectedRecords[0]}
                       :{status:1,operate_time:moment().toDate(),isfee:0,isservice:0,
                        cate_code:selectedCateNode?.title.substring(0,selectedCateNode?.title.indexOf(' ')),
                        cate_name:selectedCateNode?.title.substring(selectedCateNode?.title.indexOf(' ')),
                      }}
        >
           <Row gutter={8}>
            <Col span={8}>
            <ProFormText name='cate_code' label='分类编码'  width={300}
             rules={[{required:true,message:'必填项'}]}
            />
            <ProFormText name='cate_name' label='分类名称'  width={300} 
             rules={[{required:true,message:'必填项'}]}
            />
            <ProFormText name='code' label='物料编码' width={300} 
             rules={[{required:true,message:'必填项'}]}
              fieldProps={{
                onChange:(e)=>{
                  // alert(e.target.value);
                  setMaterialCode(e.target.value);
                }
              }}
            />
            <ProFormText name='name' label='物料名称' width={300} 
             rules={[{required:true,message:'必填项'}]}
            />
            <ProFormText name='invstd' label='规格' width={300} />
           <ProFormText name='invstd2' label='型号' width={300} />
           
           </Col>
            
            <Col span={8}>
            <ProFormRadio.Group name='isservice' label='是否服务' width={300} 
            options={[{value:1,label:'服务'},{value:0,label:'非服务'}]}
               />
           <ProFormRadio.Group name='isfee' label='是否费用'  width={300} 
           options={[{value:1,label:'费用'},{value:0,label:'非费用'}]}
                />
           <ProFormText name='scode' label='简码' width={300} />
          <ProFormSelect name='munit_id' label='主计量单位' width={300} 
              rules={[{required:true,message:'必填项'}]}
               showSearch
                  request={async ()=>{
                     const x=await s_getSelectData({x_id:1,source:'base_unit'});
                     return x.data;}}
            />
           <ProFormSelect name='aunit_id' label='辅计量单位' width={300} 
             showSearch
                  request={async ()=>{
                     const x=await s_getSelectData({x_id:1,source:'base_unit'});
                     return x.data;}}
          // fieldProps={{showSearch:true}}
           />
            <ProFormText name='rate' label='单位换算率-主/辅' width={300} />
            </Col>
            
          <Col span={8}>
          
          <ProFormText name='brand' label='品牌' width={300} />
           <ProFormRadio.Group name='status' label='状态'  width={300} 
              options={[{value:1,label:'启用'},{value:2,label:'停用'},{value:3,label:'删除'}]}
              />
          <ProFormDatePicker name='operate_time' label='操作时间' width={300} />
          <ProFormSelect name='operater_id' label='操作人' width={300} 
             showSearch
             request={async ()=>{
                    const x=await s_getSelectData({x_id:1,source:'base_person'});
                     return x.data;
               }}
          />
          <ProFormSelect name='default_warehouse_id' label='默认仓库' width={300} 
             showSearch
             request={async ()=>{
                    const x=await s_getSelectData({x_id:1,source:'base2_ware'});
                     return x.data;
               }}
          />
          <ProFormSelect name='default_whposition_id' label='默认库位' width={300} 
             showSearch
             request={async ()=>{
                    const x=await s_getSelectData({x_id:1,source:'v_warehouse_pos'});
                     return x.data;
               }}
          />
          <ProFormRadio.Group name='default_type' label='默认来源' width={300} 
            rules={[{required:true,message:'必输项'}]}
             options={[{value:1,label:'自制'},{value:2,label:'外购'},{value:3,label:'委外'}]}
          />
          </Col>
          </Row>
        </ProForm>
      </>
    },
    {
      key:'2',
      label:'自由项',
      children:<>
          <MaterialUserDefine udata={udata} setUdata={setUdata}/>
      </>
    },{
      key:'3',
      label:'附件',
      children:<>
         <Addition2 source_xid={1} setData={setAddition} type={2}
           fdata={{source_table:'addition_material',
                  //  source_id:selectedRecords==undefined||selectedRecords.length==0?0:selectedRecords[0].x_id,
                  //  source_field:'addition',
                  //  source_code:selectedRecords==undefined||selectedRecords.length==0?'':selectedRecords[0].code,
                  //  source_value:selectedRecords==undefined||selectedRecords[0]==undefined||selectedRecords.length==0?'':selectedRecords[0].addition,
                   source_id:selectedRecords==undefined||selectedRecords[0]==undefined||selectedRecords[0].id==null?''
                              :selectedRecords[0].id,
                   source_field:'addition',
                  //  source_code:selectedRecords==undefined||selectedRecords[0]==undefined||selectedRecords[0].code==null?''
                  //               :selectedRecords[0].code,
                   source_code:materialCode&&materialCode!=''?materialCode:null,
                   source_value:selectedRecords==undefined||selectedRecords[0]==undefined||selectedRecords[0].addition==null?''
                               :selectedRecords[0].addition,
           }}
         />
      </>,
    },
    {
      key:'4',
      label:'计划属性',
      children:<>
          <ProForm formRef={formref_param} submitter={false}  layout='horizontal' labelAlign='left'
           labelCol={{offset:5,span:5}}
             initialValues={etype==1?{
               isproduce:1,ispurchase:0,iscommission:0,isforcustom:0,isbatch:0,require_seq:1,stock_degree:2,
                 }:{...materialParam}}
            >
              <ProFormText name='id' hidden={true}/>
              <ProFormText name='material_id' hidden={true} />
              <Row gutter={8}>
                <Col span={12}>
                   <ProFormRadio.Group name='isproduce' label='是否自制'  width={200}
                      rules={[{required:true,message:'必填项'}]}
                      options={[{value:0,label:'否'},{value:1,label:'是'}]}
                    />
                    <ProFormRadio.Group name='ispurchase' label='是否外购' 
                      rules={[{required:true,message:'必填项'}]}
                      options={[{value:0,label:'否'},{value:1,label:'是'}]}
                    />
                    <ProFormRadio.Group name='iscommission' label='是否外加工' 
                      rules={[{required:true,message:'必填项'}]}
                      options={[{value:0,label:'否'},{value:1,label:'是'}]}
                    />
                    <ProFormSelect name='require_seq' label='需求优先级'width={200}
                       options={[
                        {value:1,label:'自制-外购-委外'},{value:2,label:'自制-委外-外购'},{value:3,label:'外购-自制-委外'},
                        {value:4,label:'外购-委外-自制'},{value:5,label:'委外-自制-外购'},{value:6,label:'委外-外购-自制'},
                       ]} />
                    <ProFormText name='forward_produce' label='生产提前期' width={200}/>
                    <ProFormText name='forward_purchase' label='生产提前期' width={200}/>
                    <ProFormText name='forward_commission' label='委外提前期' width={200}/>
                    <ProFormText name='stock_safe' label='安全库存量'    width={200}/>
                    <ProFormText name='stock_min' label='最低库存量'   width={200}/>
                    <ProFormText name='stock_max' label='最高库存量'   width={200}/>
                    
                    
                </Col>
                <Col span={12}>
                     {/* id,material_id,isproduce,ispurchase,iscommission,
              stock_min,stock_safe,stock_max,stock_dgree,cost_purchase,
              cost_produce,cost_commission,isforcustom,custom_id,quantity_batch */}
              <ProFormRadio.Group name='stock_degree' label='ABC分级' 
                      rules={[{required:true,message:'必填项'}]}
                      options={[{value:1,label:'A级'},{value:2,label:'B级'},{value:3,label:'C级'}]}
                    />
                   <ProFormRadio.Group name='isbatch' label='是否批次管理' 
                      options={[{value:0,label:'否'},{value:1,label:'是'}]} />
                   <ProFormText name='cost_produce' label='计划生产成本'   width={200}/>
                   <ProFormText name='cost_purchase' label='计划采购成本'   width={200}/>
                   <ProFormText name='cost_commission' label='计划外加工成本'   width={200}/>
                   <ProFormText name='quantity_batch' label='经济批量'  width={200} />
                   <ProFormRadio.Group name='isforcustom' label='是否店铺专用' 
                      rules={[{required:true,message:'必填项'}]}
                      options={[{value:0,label:'否'},{value:1,label:'是'}]}
                    />
                    <ProFormSelect name='custom_id' label='专用店铺'   width={200}
                        fieldProps={{
                          showSearch:true,
                        }}
                        request={async ()=>{
                          var x:any=await getSelection({source: 'v_custom', x_id: 1 });
                          var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                          return x2;
                          }}
                    />
                    <ProFormText name='ansi' label='ANSI码' width={200}/>
                    <ProFormText name='fnsku' label='FNSKU码' width={200} />
                </Col>
              </Row>
            
          </ProForm>
      </>,
    },{
      key:'custom',
      label:'店铺物料编码对照',
      children:<>
         <ProCard extra={<Space>
             <Button onClick={()=>addCompare()}>添加店铺对照</Button>
             <Button onClick={()=>editCompare()}>编辑店铺对照</Button>
         </Space>}>
         <ProTable<DataType3>
            rowKey='id'
             search={false}
            actionRef={table_ref3}
            columns={columns3}
            request={async ()=>{
              const x=await s_getTableInfo({x_id:1,source:'v_material_code_custom',
                  id:selectedRecords.length>0?selectedRecords[0].id:-1});
                // alert(JSON.stringify(x.data));
              return {
                data:x.data,
                success:true,
              }
            }}
            rowSelection={{
              type:'radio',
              onChange(selectedRowKeys, selectedRows, info) {
                  // alert(JSON.stringify(selectedRows));
                  setSelectedCompare(selectedRows);
              },
            }}
          />
      </ProCard>
      <Drawer open={dopen} title={dtype==1?'新增对照':'编辑对照'}
         closable onClose={()=>setDopen(false)}  destroyOnClose={true}
      >
           <ProForm formRef={form_ref3} submitter={false}  
              layout='horizontal' labelAlign='left'
              initialValues={dtype==0&&selectedCompare.length>0?{
                ...selectedCompare[0]
              }:{
                status:1,
              }}
              >
                <ProFormText name='material_id' hidden={true}/>
                <ProFormText name='id' hidden={true}/>
                <ProFormSelect name='custom_id' label='店铺' width={200} rules={[{required:true,message:'必填项'}]}
                     fieldProps={{
                      showSearch:true,
                    }}
                    request={async ()=>{
                      var x:any=await getSelection({source: 'v_custom', x_id: 1 });
                      var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                      return x2;
                      }}
                />
                <ProFormText name='cmaterial_code' label='店铺物料编码'  width={200}
                 rules={[{required:true,message:'必填项'}]}
                />
                <ProFormRadio.Group name='status' label='状态'
                   options={[{value:1,label:'有效'},{value:2,label:'冻结'},{value:3,label:'删除'}]}
                   />
            </ProForm>
            <Row gutter={8}>
              <Col span={12}><Button   onClick={()=>saveCompare(1)}>保存对照</Button></Col>
              <Col span={12}><Button   onClick={()=>saveCompare(2)}>保存并继续</Button></Col>
            </Row>
      </Drawer>
      </>
    }
  ];

  //退出物料编辑
  function eixtMaterialInfo(){
      setMaterialParam({});
      setSelectedCompare([]);
      setOpenInfo(false);
  };

  //==================================================================================================
  return<>
     <Row gutter={10}>
     <Col  span={5}>
     <Card title='物料分类' style={{height:'75vh'}}>
         <Tree treeData={treeData} expandedKeys={expandKeys} 
         onExpand={(ekeys:any)=>setExpandKeys(ekeys)}
          onClick={(e,node)=>getMaterial(node)}
         />
     </Card>
     </Col>
     <Col  span={19}>
      <Card title='物料档案'  style={{height:'75vh'}} id='drawer_id'
      extra={<Space size='large'>
      <Button  onClick={()=>addMaterialInfo()}>新增物料档案</Button>
      <Button  onClick={()=>editMaterialInfo()}>修改物料档案</Button>
      {/* <Button  onClick={()=>allocateOrg()}>分配组织</Button> */}
      
      </Space>}
      >
     
       <ProTable 
      // dataSource={props.tdata} 
      columns={columns} 
      rowKey='id' 
      rowSelection={{
        type:'radio',
        onChange:(selectedKeys,selectedRows:any)=>{
          setMaterialCode(selectedRows)},
      }}
         scroll={{y:'55vh'}}
         options={false}
         actionRef={table_ref}
         search={false}
         request={async (param)=>{
            const x=await s_getMaterialDocument({x_id:1,cate_id:treeCate?treeCate:[],id:0});
            return  {
                     data:x.data[0],
                      success:true
                    };
         }}
       />

      </Card>
      </Col>
     </Row>

    
     <Modal title='物料维护' open={openInfo}  width='80%'   maskClosable={false}  okButtonProps={{hidden:true}}
         destroyOnClose={true} closable={true} onCancel={()=>eixtMaterialInfo()}
         onClose={()=>eixtMaterialInfo()}
         cancelButtonProps={{hidden:true}}
     >  
       <ProCard 
          style={{height:800,overflow:'auto'}} 
          extra={<Space size='large'>
            <Button onClick={()=>saveMaterialInfo()} >保存</Button>
            <Button onClick={()=>eixtMaterialInfo()}>取消</Button>
          </Space>}  >
          {/* {JSON.stringify(selectedRecords)} */}
       <Tabs items={items}   style={{height:520}}  />
       </ProCard>  
     </Modal>

     
  </>
};

export default Welcome;


